package org.mybatis.spring;

import com.kevin.mapper.MemberMapper;
import com.kevin.mapper.OrderMapper;
import com.kevin.mapper.UserMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的Bean定义方法
 */
public class KevinImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        // 扫描 1. 扫描的路径
        String path = "com.kevin.mapper";
        KevinMapperScan kevinMapperScan = new KevinMapperScan(registry);
        /**
         * 添加自定义的扫描过滤器
         */
        kevinMapperScan.addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                return true;
            }
        });

        int scan = kevinMapperScan.scan(path);

        System.out.println(scan);

        List<Class> mapperList = new ArrayList<>();
        mapperList.add(UserMapper.class);
        mapperList.add(OrderMapper.class);
        mapperList.add(MemberMapper.class);

        for (Class mapper : mapperList) {

            // 编程式定义
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(mapper);
            beanDefinition.setBeanClass(KevinFactoryBean.class);

            registry.registerBeanDefinition(mapper.getName(), beanDefinition);
        }
    }
}
